//
//  SelectMemberViewController.m
//  fitnessmanage
//
//  Created by wujian on 2018/1/4.
//  Copyright © 2018年 zongquankeji. All rights reserved.
//

#import "SelectMemberViewController.h"
#import "VenueVipTableViewCell.h"
#import "ChineseString.h"

@interface SelectMemberViewController ()<UITableViewDataSource,UITableViewDelegate>{
    
    NSString *selectStr;
    
    int startIndex;
    
    int pageSize;
}

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong) NSMutableArray *indexArray;

@property(nonatomic,strong) NSMutableArray *letterResultArr;

@property (nonatomic, strong) UILabel *sectionTitleView;

@property (nonatomic, strong) NSMutableArray *stringsToSort;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property(nonatomic,strong)NoDataView *noDataView;

@property (nonatomic, strong) NSMutableDictionary *dataDict;

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation SelectMemberViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
 
    self.title = @"选择会员";
    
    self.indexArray = [ChineseString IndexArray:self.stringsToSort];
    
    self.letterResultArr = [ChineseString LetterSortArray:self.stringsToSort];
    
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    
    [self createSubView];
}

-(void)createSubView{
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 200;
    [tableView registerClass:[VenueVipTableViewCell class] forCellReuseIdentifier:@"VenueVipTableViewCell"];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.backgroundColor = BackGroundColor;
    //修改索引颜色
    tableView.sectionIndexColor = CSColorFromRGB(0x0a0a0a);//修改右边索引字体的颜色
    tableView.sectionIndexTrackingBackgroundColor = CSClearColor;//修改右边索引点击颜色
    [self.view addSubview:tableView];
    MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
    tableView.mj_header = mj_head;
    //tableView.mj_footer = footer;
    [tableView.mj_header beginRefreshing];
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(self.view);
    }];
    self.tableView = tableView;
    
    //默认字母排序
    selectStr = @"characterSort";
    
}

#pragma mark 下拉
-(void)loadStartData{
    
    startIndex = 1;
    
    pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    startIndex = startIndex + 1;
    
    [self loadData];
}

-(void)loadData{
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    BrandModel *brand = [BrandModel brand];
    
    [params setObject:brand.brandID forKey:@"BrandID"];
    
    VenueModel *venue = [VenueModel venue];
    
    [params setObject:venue.venueId forKey:@"ShopID"];
    
    [params setObject:[NSString stringWithFormat:@"%d",startIndex] forKey:@"page"];
    
    [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
    
    NSString *url = Get_UsersListData;
    
    if (self.memberUrl) {
        
        url = self.memberUrl;
    }
    
    [HTTPTool GET:url parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  if (resultArray.count > 0) {
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }
                  
                  self.noDataView = [NoDataView shareInstance];
                  
                  [self.noDataView hideInView:self.view];
                  
                  
                  if (startIndex == 1) {
                      
                      self.dataArray = [NSMutableArray arrayWithArray:resultArray];
                      
                      if (self.dataArray.count == 0) {
                          
                          self.noDataView = [NoDataView shareInstance];
                          
                          [self.noDataView showInView:self.view];
                      }
                      
                      [self.stringsToSort removeAllObjects];
                      
                      [self.dataDict removeAllObjects];
                      
                      for (NSDictionary *dict in self.dataArray) {
                          
                          NSString *name;
                          
                          if ([[dict objectForKey:@"Name"] isEqual:[NSNull null]]) {
                              
                              name = @"#";
                          }
                          else{
                              
                              name = [dict objectForKey:@"Name"];
                          }
                          //后面取数据要用到ID，但是ID不影响排序
                          [self.stringsToSort addObject:[NSString stringWithFormat:@"%@\\%@",name,[dict objectForKey:@"ID"]]];
                      }
                  }
                  else{
                      
                      [self.dataArray addObjectsFromArray:resultArray];
                      
                      for (NSDictionary *dict in resultArray) {
                          
                          NSString *name;
                          
                          if ([[dict objectForKey:@"Name"] isEqual:[NSNull null]]) {
                              
                              name = @"#";
                          }
                          else{
                              
                              name = [dict objectForKey:@"Name"];
                          }
                          //后面取数据要用到ID，但是ID不影响排序
                          [self.stringsToSort addObject:[NSString stringWithFormat:@"%@\\%@",name,[dict objectForKey:@"ID"]]];
                      }
                  }
                  
                  self.indexArray = [ChineseString IndexArray:self.stringsToSort];
                  //
                  self.letterResultArr = [ChineseString LetterSortArray:self.stringsToSort];
                  //
                  
                  for (NSDictionary *dict in self.dataArray) {
                      
                      NSString *key = [NSString stringWithFormat:@"%@",[dict objectForKey:@"ID"]];
                      
                      [self.dataDict setObject:dict forKey:key];
                  }
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma mark - UITableViewDataSource
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        return self.indexArray;
    }
    else{
        
        return nil;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        NSString *key = [self.indexArray objectAtIndex:section];
        
        return key;
    }
    else{
        
        return nil;
    }
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        return [self.indexArray count];
    }
    else{
        
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        return [[self.letterResultArr objectAtIndex:section] count];
    }
    else{
        
        return self.stringsToSort.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VenueVipTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VenueVipTableViewCell"];
    
    NSDictionary *dict;
    
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        //resultArry =[self.letterResultArr objectAtIndex:indexPath.section];
        NSString *name = [[self.letterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        
        NSString *ID = [[name componentsSeparatedByString:@"\\"] lastObject];
        
        dict = [self.dataDict objectForKey:ID];
    }
    else{
        
        //resultArry = self.stringsToSort;
        dict = [self.dataArray objectAtIndex:indexPath.row];
    }
    
    UserAccount *userModel = [UserAccount mj_objectWithKeyValues:dict];
    
    cell.nickNameLabel.text = userModel.Name?userModel.Name:@" ";
    
    if ([userModel.Sex integerValue] == 0) {
        
        cell.sexBtn.selected = YES;
    }
    else{
        
        cell.sexBtn.selected = NO;
    }
    
    cell.phoneLabel.text = [NSString stringWithFormat:@"联系电话：%@",userModel.CellPhone];
    
    cell.ageBtn.hidden = YES;
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",userModel.Pic,mid_image];
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:PlaceHold];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        [self showSectionTitle:title];
        
    }
    
    return index;
}

#pragma mark UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        return 30;
    }
    else{
        
        return CGFLOAT_MIN;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *head = (UITableViewHeaderFooterView *)view;
    head.backgroundColor = BackGroundColor;
    [head.textLabel setTextColor:CSColorFromRGB(0x000000)];
    head.textLabel.font = BigFont;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict;
    
    if ([selectStr isEqualToString:@"characterSort"]) {
        
        //resultArry =[self.letterResultArr objectAtIndex:indexPath.section];
        NSString *name = [[self.letterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        
        NSString *ID = [[name componentsSeparatedByString:@"\\"] lastObject];
        
        dict = [self.dataDict objectForKey:ID];
    }
    else{
        
        dict = [self.dataArray objectAtIndex:indexPath.row];
    }
    
    UserAccount *userModel = [UserAccount mj_objectWithKeyValues:dict];
    
    if (self.sendUserBlock) {
        
        self.sendUserBlock(userModel);
        
        [self back];
    }
}

#pragma mark - private
- (void)timerHandler:(NSTimer *)sender
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:.3 animations:^{
            self.sectionTitleView.alpha = 0;
        } completion:^(BOOL finished) {
            self.sectionTitleView.hidden = YES;
        }];
    });
}

-(void)showSectionTitle:(NSString*)title{
    
    [self.sectionTitleView setText:title];
    
    self.sectionTitleView.hidden = NO;
    
    self.sectionTitleView.alpha = 1;
    
    [self.timer invalidate];
    
    self.timer = nil;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerHandler:) userInfo:nil repeats:NO];
    
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

#pragma mark Get

-(UILabel *)sectionTitleView{
    
    if (!_sectionTitleView) {
        
        _sectionTitleView = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-100)/2, (SCREEN_HEIGHT-100)/2,100,100)];
        _sectionTitleView.textAlignment = NSTextAlignmentCenter;
        _sectionTitleView.font = [UIFont boldSystemFontOfSize:60];
        _sectionTitleView.textColor = [UIColor blueColor];
        _sectionTitleView.backgroundColor = CSWhiteColor;
        _sectionTitleView.layer.cornerRadius = 6;
        _sectionTitleView.layer.borderWidth = 1.f/[UIScreen mainScreen].scale;
        _sectionTitleView.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
        [self.view addSubview:_sectionTitleView];
        _sectionTitleView.hidden = YES;
    }
    
    return _sectionTitleView;
}

-(NSMutableArray *)dataArray{
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
    }
    
    return _dataArray;
}

-(NSMutableDictionary *)dataDict{
    
    if (!_dataDict) {
        
        _dataDict = [[NSMutableDictionary alloc] init];
    }
    
    return _dataDict;
}

-(NSMutableArray *)stringsToSort{
    
    if (!_stringsToSort) {
        
        _stringsToSort = [[NSMutableArray alloc] init];
    }
    
    return _stringsToSort;
}

#pragma mark 后退
-(void)back{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
